import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
     }
  }


 class Solution {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> listVal = new ArrayList<>();

        if (root == null) {
            return listVal;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size != 0) {
                TreeNode out = queue.poll();
                list.add(out.val);
                if (out.left != null) {
                    queue.offer(out.left);
                }
                if (out.right != null) {
                    queue.offer(out.right);
                }
                size--;
            }
            listVal.add(list);
        }
        return listVal;
    }
}